﻿using AutoMapper;
using MediatR;
using Traceability.App.Api.Application.Command.Add;
using Traceability.App.Domain;
using Traceability.App.ErrorCode;
using Traceability.App.Instructure;

namespace Traceability.App.Api.Application.Handler.Add
{
    /// <summary>
    /// 修改添加养殖信息
    /// </summary>
    public class AddAquacultureHandler : IRequestHandler<AddAquacultureCommand, ApiResult<int>>
    {
        private readonly IBaseRepository<Aquaculture> aquacultureRepo;
        private readonly IMapper mapper;
        private readonly IBaseRepository<TraceabilityModel> traceabilityRepo;

        public AddAquacultureHandler(IBaseRepository<Aquaculture> aquacultureRepo,IMapper mapper,IBaseRepository<TraceabilityModel> traceabilityRepo) 
        {
            this.aquacultureRepo = aquacultureRepo;
            this.mapper = mapper;
            this.traceabilityRepo = traceabilityRepo;
        }
        public Task<ApiResult<int>> Handle(AddAquacultureCommand request, CancellationToken cancellationToken)
        {
            ApiResult<int> res = new ApiResult<int>();
            var aquacultures = aquacultureRepo.GetAll().Where(x => x.Batch == request.Batch).FirstOrDefault();
            if (aquacultures == null)
            {
                var entity = mapper.Map<Aquaculture>(request);
                aquacultureRepo.Add(entity);
            }
            else
            {
                aquacultures.KeepersBrand = request.KeepersBrand;
                aquacultures.BreedName = request.BreedName;
                aquacultures.ChuDateTime = request.ChuDateTime;
                aquacultures.KeepersDay = request.KeepersDay;
                aquacultures.KeepersPerson = request.KeepersPerson;
                aquacultures.Origin = request.Origin;
                aquacultures.UpdateName = "张三";
                aquacultures.UpdateTime = DateTime.Now;
                aquacultures.CreateName = "张三";
                aquacultures.CreateTime = DateTime.Now;
                aquacultureRepo.Update(aquacultures);
            }
             res.Code = ApiEnum.Success;
             res.Msg = "修改养殖信息成功";
            return Task.FromResult(res);
        }
    }
}
